package osSRC.banker;

import java.util.Scanner;

class Sequence {
	private int processCount;
	private int loopTimeLimit;
	private int loopTime;
	private int[] sequence;
	Sequence(){}
	Sequence(int processCount){
		this.processCount=processCount;
		this.sequence=new int[processCount];
		this.initSequence();
		this.loopTimeLimit=fac(this.processCount);
		this.loopTime=1;
	}
	public int getLoopTimeLimit() {
		return loopTimeLimit;
	}
	private void initSequence(){
		for(int i=0;i<this.sequence.length;i++){
			this.sequence[i]=i;
		}
	}
	static int fac(int n){
		if(n<0)return 0;
		else if (n<2)return 1;
		else return n*fac(n-1);
	}
	private void swap(int num1,int num2){
		int temp;
		if(num1>this.processCount||num2>this.processCount){
			System.out.println("swap:number too large");
			return;
		}
		temp=this.sequence[num1];
		this.sequence[num1]=this.sequence[num2];
		this.sequence[num2]=temp;
	}
	void findNextSequence(boolean sequenceToInit){
		int i,j,k1,temp_low;
		Scanner scanner=new Scanner(System.in);
		if(this.loopTime>=this.loopTimeLimit) {
			System.out.println("All Sequence possibilities listed");
			if(scanner.nextLine().equals("q"))System.exit(0);
		}
		if(sequenceToInit){
			show();
			initSequence();
			this.loopTime=1;
		}
		else {
			i=0;
			try{
				this.loopTime++;
				for (i = processCount - 2; i >= 0; i--) {
					if (this.sequence[i] < this.sequence[i + 1])
						break;
					//orthodox-record i in k1
				}
				k1 = i;
				temp_low = i + 1;
				for (i = k1 + 1; i < processCount; i++) {
					if (this.sequence[i] > this.sequence[k1] &&
							this.sequence[i] < this.sequence[temp_low])
						temp_low = i;
				}//find the index of the lowest num over k1-indexed num
				swap(k1, temp_low);

				for (j = k1 + 1, i = processCount - 1;
					 i > j;
					 i--, j++) {
					swap(i, j);
				}
			}
			catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException){
				System.out.println("Array out of bounds: i="+i);
			}
		}
	}
	void show(){
		for(int i:this.sequence){
			System.out.printf("%d\t",i);
		}
		System.out.println("\tSequence No. "+this.loopTime);
	}

	int getSequenceIndex(int index){
		return this.sequence[index];
	}

}
